// src/backtesting/data-provider.ts
import { MarketDataService, FormattedKlineData, KlineBar } from '../services/market-data.service';
import { formatToUTC8 } from '../utils/time.utils';

/**
 * 获取并准备回测所需的历史数据
 * @param marketDataService - MarketDataService的实例
 * @param symbol - 交易对
 * @param timeframe - K线周期
 * @param startDate - 开始日期
 * @param endDate - 结束日期
 * @returns - 排序好的K线数据
 */
export async function prepareData(
  marketDataService: MarketDataService,
  symbol: string,
  timeframe: KlineBar,
  startDate: Date,
  endDate: Date
): Promise<FormattedKlineData[]> {
  console.log(`
Fetching historical data for ${symbol} from ${formatToUTC8(startDate)} to ${formatToUTC8(endDate)}...`);

  const rawKlines = await marketDataService.getKlinesForDateRange(symbol, timeframe, startDate, endDate);

  if (!rawKlines || rawKlines.length === 0) {
    console.error("Failed to fetch historical data for the specified date range.");
    return [];
  }

  const formattedKlines: FormattedKlineData[] = rawKlines.map(kline => ({
    timestamp: parseInt(kline[0]),
    open: parseFloat(kline[1]),
    high: parseFloat(kline[2]),
    low: parseFloat(kline[3]),
    close: parseFloat(kline[4]),
    volume: parseFloat(kline[5]),
    volumeCcy: parseFloat(kline[6]),
    volumeCcyQuote: parseFloat(kline[7]),
    confirmed: kline[8] === '1'
  })).filter(k => k.confirmed);

  return formattedKlines;
}
